<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TLDW Server - First-Time Setup</title>
    <link rel="stylesheet" href="/webui/css/styles.css">
    <link rel="stylesheet" href="/webui/css/setup.css">
    <script defer src="/webui/js/setup-guard.js"></script>
    <!-- Inline handler shim removed after migrating handlers to modules -->
    <script defer src="/webui/js/setup.js"></script>
</head>
<body class="setup-body">
    <div class="setup-layout">
        <header class="setup-header">
            <h1>Welcome to tldw_server</h1>
            <p>Your instance is running with default configuration. Use this guided setup to add API keys, adjust authentication, and review important settings before continuing.</p>
        </header>

        <section id="setupStatus" class="setup-section status-section">
            <div class="status-content">
                <h2>Setup Checklist</h2>
                <div class="status-grid">
                    <div>
                        <span class="status-label">Configuration file</span>
                        <span id="configPath" class="status-value">Loading…</span>
                    </div>
                    <div>
                        <span class="status-label">Setup required</span>
                        <span id="setupRequired" class="status-badge">-</span>
                    </div>
                </div>
                <div id="placeholderNotice" class="status-notice" hidden></div>
            </div>
        </section>

        <section id="guidedWizard" class="setup-section wizard-section" hidden>
            <div class="section-heading">
                <h2>Guided Setup</h2>
                <p>Answer a few quick questions so we can highlight the settings that matter most. You can always skip and edit everything manually.</p>
            </div>
            <div id="wizardProgress" class="wizard-progress" aria-live="polite"></div>
            <div id="wizardMessage" class="wizard-message" role="alert" aria-live="assertive" hidden></div>
            <div id="wizardContent" class="wizard-content"></div>
            <div class="wizard-footer">
                <button id="wizardBack" class="btn subtle" type="button" disabled>Back</button>
                <div class="wizard-actions">
                    <button id="wizardSkip" class="btn subtle" type="button">Skip &amp; Show All Settings</button>
                    <button id="wizardNext" class="btn primary" type="button">Next</button>
                </div>
            </div>
        </section>

        <section id="configSection" class="setup-section" hidden>
            <div class="section-heading">
                <h2>Configuration Explorer</h2>
                <p>Review each section below. Update any values that still use placeholders or defaults.</p>
            </div>
            <div id="wizardSummary" class="wizard-summary" hidden></div>
            <div id="moduleWalkthroughs" class="module-walkthroughs" hidden>
                <div class="module-walkthrough-header">
                    <h3>Module Walkthroughs</h3>
                    <p>Optional deep dives for complex areas. Jump in when you want hands-on guidance.</p>
                </div>
                <div id="moduleWalkthroughList" class="module-walkthrough-list"></div>
            </div>
            <button id="showAllSections" class="btn subtle show-all" type="button" hidden></button>
            <div id="configSections" class="config-sections">
                <div class="empty-state" id="configLoading">Loading configuration…</div>
            </div>
        </section>

        <section class="setup-section">
            <div class="section-heading">
                <h2>Actions</h2>
                <p>Save your changes before marking setup as complete. Restart the server after finishing to apply new settings.</p>
            </div>
            <div class="action-row">
                <button id="saveChanges" class="btn primary" disabled>Save Changes</button>
                <label class="toggle-option">
                    <input type="checkbox" id="disableWizardToggle">
                    Disable guided setup after completion
                </label>
                <button id="completeSetup" class="btn success" disabled>Mark Setup Complete</button>
                <button id="resetSetup" class="btn subtle danger" type="button" title="Admin only; resets setup flags">Reset Setup Flags</button>
            </div>
            <div id="actionMessage" class="action-message" role="status"></div>
            <div id="installStatusPanel" class="install-status-panel" hidden aria-live="polite">
                <div class="install-status-header">
                    <h3 id="installStatusHeading">Installer Progress</h3>
                    <span id="installStatusState" class="status-badge">Idle</span>
                </div>
                <p id="installStatusMessage" class="install-status-message"></p>
                <div id="installStatusLog" class="install-status-log"></div>
            </div>
        </section>

        <section id="verifySection" class="setup-section">
            <div class="section-heading">
                <h2>Verify Access</h2>
                <p>If you just created an account, you can verify it locally during setup. Provide an access token (JWT) or an API key.</p>
            </div>
            <div class="verify-grid">
                <div class="verify-field">
                    <label for="verifyToken">Access Token (JWT):</label>
                    <input type="password" id="verifyToken" placeholder="Paste access token or leave blank if using API key" />
                </div>
                <div class="verify-field">
                    <label for="verifyApiKey">API Key (X-API-KEY):</label>
                    <input type="password" id="verifyApiKey" placeholder="Paste API key or leave blank if using JWT" />
                </div>
            </div>
            <div class="verify-actions">
                <button id="verifySubmit" class="btn primary" type="button">Verify</button>
                <span id="verifyMsg" class="verify-msg" role="status" aria-live="polite"></span>
            </div>
            <script>
                document.getElementById('verifySubmit').addEventListener('click', async () => {
                    const msg = document.getElementById('verifyMsg');
                    msg.textContent = 'Verifying…';
                    msg.style.color = '';

                    const tokenInput = document.getElementById('verifyToken');
                    const apiKeyInput = document.getElementById('verifyApiKey');

                    // Try to populate token from localStorage if empty
                    if (tokenInput && !tokenInput.value) {
                        try {
                            const saved = localStorage.getItem('tldw_access_token');
                            if (saved) tokenInput.value = saved;
                        } catch {}
                    }

                    const headers = { 'Content-Type': 'application/json' };
                    const token = (tokenInput && tokenInput.value) ? tokenInput.value.trim() : '';
                    const apiKey = (apiKeyInput && apiKeyInput.value) ? apiKeyInput.value.trim() : '';

                    if (token) {
                        headers['Authorization'] = `Bearer ${token}`;
                    } else if (apiKey) {
                        headers['X-API-KEY'] = apiKey;
                    } else {
                        msg.textContent = 'Provide an access token or an API key.';
                        msg.style.color = '#b00020';
                        return;
                    }

                    try {
                        const r = await fetch('/api/v1/setup/self-verify', {
                            method: 'POST',
                            headers
                        });
                        const data = await r.json();
                        if (!r.ok) throw new Error(data.detail || r.statusText);
                        msg.textContent = 'Account verified successfully. You may need to refresh the page.';
                        msg.style.color = '#107c10';
                    } catch (e) {
                        msg.textContent = 'Verification failed: ' + (e && e.message ? e.message : e);
                        msg.style.color = '#b00020';
                    }
                });
            </script>
        </section>
    </div>

    <div id="assistantRoot" class="assistant-root" aria-live="polite">
        <button id="assistantToggle" class="assistant-toggle" type="button" aria-expanded="false" aria-controls="assistantPanel">
            <span class="assistant-icon" aria-hidden="true">🤖</span>
            <span class="assistant-label">Setup Assistant</span>
        </button>
        <div id="assistantPanel" class="assistant-panel" role="dialog" aria-modal="false" aria-labelledby="assistantTitle" hidden>
            <header class="assistant-header">
                <div id="assistantTitle" class="assistant-title">
                    <span class="assistant-icon" aria-hidden="true">🤖</span>
                    <span>Setup Assistant</span>
                </div>
                <button id="assistantClose" class="assistant-close" type="button" aria-label="Close assistant">×</button>
            </header>
            <div id="assistantMessages" class="assistant-messages" role="log" aria-live="polite"></div>
            <div id="assistantTyping" class="assistant-typing" hidden>Thinking…</div>
            <form id="assistantForm" class="assistant-form">
                <label class="sr-only" for="assistantInput">Ask a question about configuration</label>
                <textarea id="assistantInput" class="assistant-input" name="question" rows="2" placeholder="Ask how to configure something…" required></textarea>
                <div class="assistant-actions">
                    <button id="assistantSend" class="btn primary assistant-send" type="submit">Send</button>
                </div>
            </form>
        </div>
    </div>

    <div id="moduleOverlay" class="module-overlay" role="dialog" aria-modal="true" aria-labelledby="moduleOverlayTitle" tabindex="-1" hidden>
        <div class="module-overlay-content">
            <header class="module-overlay-header">
                <div class="module-overlay-title-group">
                    <span class="module-overlay-icon" aria-hidden="true">🧭</span>
                    <h3 id="moduleOverlayTitle" class="module-overlay-title"></h3>
                </div>
                <button id="moduleOverlayClose" class="module-overlay-close" type="button" aria-label="Close walkthrough">×</button>
            </header>
            <p id="moduleOverlayIntro" class="module-overlay-intro"></p>
            <div class="module-overlay-step-status">
                <span id="moduleOverlayStep"></span>
            </div>
            <div id="moduleOverlayBody" class="module-overlay-body"></div>
            <footer class="module-overlay-footer">
                <button id="moduleOverlayBack" class="btn subtle" type="button">Back</button>
                <div class="module-overlay-actions">
                    <button id="moduleOverlaySkip" class="btn subtle" type="button">Skip walkthrough</button>
                    <button id="moduleOverlayNext" class="btn primary" type="button">Next</button>
                </div>
            </footer>
        </div>
    </div>
</body>
</html>
